package com.hanliy.storage.impl;

import com.hanliy.storage.StorageType;
import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author hanyulin
 * @apiNote 本地图片上传
 * @date 2021/11/15 17:22
 */
@Data
public class LocalStorageImpl implements StorageType {

    private String storagePath;
    private String address;

    private Path rootLocation;

    /**
     * 创建图片的存储目录
     */
    public void setStoragePath(String storagePath) {
        this.storagePath = storagePath;

        this.rootLocation = Paths.get(storagePath);
        try {
            Files.createDirectories(rootLocation);
        } catch (IOException e) {
            e.getMessage();
        }
    }

    @Override
    public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
        try {
            Files.copy(inputStream, rootLocation.resolve(keyName), StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file " + keyName, e);
        }
    }

    @Override
    public String generateUrl(String keyName) {
        return address + keyName;
    }

    @Override
    public void delete(String key) {
        Path file = rootLocation.resolve(key);
        try {
            Files.delete(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
